package com.vstudy.zx.service.impl;

import com.vstudy.zx.dao.ArticleDao;
import com.vstudy.zx.dao.OutlineDao;
import com.vstudy.zx.dao.StudentDao;
import com.vstudy.zx.dao.TeacherDao;
import com.vstudy.zx.entity.Article;
import com.vstudy.zx.entity.Outline;
import com.vstudy.zx.entity.Student;
import com.vstudy.zx.entity.Teacher;
import com.vstudy.zx.service.SearchService;
import com.vstudy.zx.utils.IOUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;

@Service
@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
public class SearchServiceImpl implements SearchService {
    @Autowired
    private ArticleDao articleDao;
    @Autowired
    private OutlineDao outlineDao;
    @Autowired
    private TeacherDao teacherDao;
    @Autowired
    private StudentDao studentDao;

    @Override
    public List<Article> getArticles(String key, HttpServletRequest request) {
        List<Article> articles = articleDao.selectByTitle(key);
        for (Article a :
                articles) {
            String realPath = request.getServletContext().getRealPath(a.getArticle_content());
            try {
                String html = IOUtil.readArticle(realPath, "utf-8");
                a.setArticle_content(html);
            } catch (IOException e) {
                e.printStackTrace();
            }
            a.releaseTime = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(a.getArticle_release_time());
        }
        return articles;
    }

    @Override
    public List<Outline> getOutlines(String key) {
        return outlineDao.selectByKeyWord(key);
    }

    @Override
    public List<Teacher> getTeachers(String key) {
        return teacherDao.selectByKeyLoginName(key);
    }

    @Override
    public List<Student> getStudents(String key) {
        return studentDao.selectByKeyName(key);
    }
}
